package icu.groot.alan.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.groot.alan.service.UserService;
import icu.groot.alan.service.impl.UserServiceImpl;
import icu.groot.alan.util.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String code = req.getParameter("code");
        String password = req.getParameter("password");
        ObjectMapper objectMapper = new ObjectMapper();
        //校验参数
        if (StringUtils.isAnyBlank(code, password)) resp.getWriter().print(R.error("参数丢失"));
        //访问数据库
        UserService userService = new UserServiceImpl();
        R result = userService.login(code, password);
        if (result.getData() == null){
            resp.getWriter().print(objectMapper.writeValueAsString(result));
            return;
        }

        //设置cookie
        Cookie cookie = new Cookie("token", result.getData().toString());
        //cookie存活时间
        cookie.setMaxAge(19 * 60);
        resp.addCookie(cookie);
        resp.getWriter().print(objectMapper.writeValueAsString(result));
    }
}
